// 路由文件4个步骤
// 1.加载express
const express = require('express');
// 加载加密模块
const utility = require('utility');
// 加载jsonwebtoken模块  用于生产token字符串
const jsonwebtoken = require('jsonwebtoken');
const path = require('path');
const db = require(path.join(__dirname, '../utils', 'db'));
// 2.创建路由对象
const router = express.Router();
// 3.把接口挂载到路由对象上
// ------------------  这里写接口  -----------------
router.post('/reguser', async(req, res) => {
    req.body.password = utility.md5(req.body.password);
    let r = await db('insert into user set ?', req.body);
    if (r && r.affectedRows > 0) {
        res.send({
            status: 0,
            message: '注册成功',
        });
    } else {
        res.send({
            status: 1,
            message: '注册失败',
        });
    }
});
router.post('/login', async(req, res) => {
    let username = req.body.username;
    let password = utility.md5(req.body.password);
    let r = await db('select * from user where username=? and password=?', [
        username,
        password,
    ]);
    // console.log(r);
    if (r && r.length > 0) {
        res.send({
            status: 0,
            message: '登录成功',
            token: 'Bearer ' +
                jsonwebtoken.sign({ username: req.body.username, id: r[0].id },
                    'bigevent', {
                        expiresIn: '2 days',
                    }
                ),
        });
    } else {
        res.send({
            status: 1,
            message: '登录失败',
        });
    }
});
// 4.导出路由对象
module.exports = router;